package com.smart.community.region.service.impl;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.smart.community.commons.cache.DataScopeInfo;
import com.smart.community.commons.utils.SecurityUtils;
import com.smart.community.feign.property.service.DataScopeFeign;
import com.smart.community.region.entity.Building;
import com.smart.community.region.entity.Community;
import com.smart.community.region.entity.Household;
import com.smart.community.region.entity.Unit;
import com.smart.community.region.mapper.BuildingMapper;
import com.smart.community.region.mapper.CommunityMapper;
import com.smart.community.region.mapper.HouseholdMapper;
import com.smart.community.region.mapper.UnitMapper;
import com.smart.community.region.service.IDataImportService;
import com.smart.community.region.utils.DataValidationUtils;

import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;

/**
 * 数据导入服务实现类
 * 
 * @author Wu.Liang
 * @since 2025-01-30
 */
@Slf4j
@Service
public class DataImportServiceImpl implements IDataImportService {

	@Autowired
	private BuildingMapper buildingMapper;

	@Autowired
	private UnitMapper unitMapper;

	@Autowired
	private HouseholdMapper householdMapper;

	@Autowired
	private CommunityMapper communityMapper;

	@Autowired
	private DataScopeFeign dataScopeFeign;

	@Autowired
	private DataValidationUtils dataValidationUtils;

	@Override
	@GlobalTransactional(rollbackFor = Exception.class)
	public ImportResult importCommunityData(Map<String, List<Map<String, Object>>> data, Long communityId, Long userId,
			Boolean overwrite, Boolean skipErrors) {
		long startTime = System.currentTimeMillis();
		ImportResult result = new ImportResult();

		try {
			// 参数验证
			if (data == null || data.isEmpty()) {
				log.warn("导入数据为空，返回失败结果");
				result.setSuccess(false);
				result.setMessage("导入数据为空");
				return result;
			}

			if (userId == null) {
				log.warn("用户ID为空，返回失败结果");
				result.setSuccess(false);
				result.setMessage("用户ID为空");
				return result;
			}

			List<Map<String, Object>> buildings = data.get("buildings");
			List<Map<String, Object>> units = data.get("units");
			List<Map<String, Object>> households = data.get("households");

			// 智能识别社区
			Long identifiedCommunityId = identifyCommunity(buildings, units, households, communityId);
			if (identifiedCommunityId == null) {
				result.setSuccess(false);

				// 获取当前用户ID和权限信息，提供更详细的错误信息
				Long currentUserId = SecurityUtils.getCurrentUserId();
				String errorMessage = "无法识别目标社区，请检查模板中的社区名称或手动选择社区";

				if (currentUserId != null) {
					try {
						DataScopeInfo dataScopeInfo = dataScopeFeign.getUserDataScope(currentUserId);
						if (dataScopeInfo != null) {
							List<Long> accessibleCommunityIds = dataScopeInfo.getCommunityIds();
							if (accessibleCommunityIds == null || accessibleCommunityIds.isEmpty()) {
								errorMessage = "您没有社区权限，请联系管理员分配社区权限";
							} else {
								// 获取用户可访问的社区名称列表
								List<String> accessibleCommunityNames = getAccessibleCommunityNames(
										accessibleCommunityIds);
								if (!accessibleCommunityNames.isEmpty()) {
									errorMessage = String.format("无法识别目标社区，请确保模板中的社区名称在您的权限范围内。您可访问的社区：%s",
											String.join("、", accessibleCommunityNames));
								}
							}
						}
					} catch (Exception e) {
						log.warn("获取用户权限信息失败，使用默认错误信息", e);
					}
				}

				result.setMessage(errorMessage);
				return result;
			}

			log.info("智能识别社区成功，社区ID：{}", identifiedCommunityId);

			// 数据验证
			DataValidationUtils.ValidationResult buildingValidation = dataValidationUtils
					.validateBuildingData(buildings, identifiedCommunityId);
			DataValidationUtils.ValidationResult unitValidation = dataValidationUtils.validateUnitData(units, buildings,
					identifiedCommunityId);
			DataValidationUtils.ValidationResult householdValidation = dataValidationUtils
					.validateHouseholdData(households, buildings, units, identifiedCommunityId);

			// 检查验证结果
			if (buildingValidation.hasErrors() || unitValidation.hasErrors() || householdValidation.hasErrors()) {
				result.setSuccess(false);
				result.setMessage("数据验证失败，请检查错误信息");
				result.setBuildingErrors(buildingValidation.getErrors());
				result.setUnitErrors(unitValidation.getErrors());
				result.setHouseholdErrors(householdValidation.getErrors());
				return result;
			}

			// 重复性检查（在验证阶段进行）
			if (!Boolean.TRUE.equals(overwrite) && !Boolean.TRUE.equals(skipErrors)) {
				// 严格模式：检查是否有重复数据
				List<String> buildingNos = buildings.stream().map(building -> (String) building.get("buildingNo"))
						.collect(Collectors.toList());

				List<Building> existingBuildings = buildingMapper.selectByBuildingNosAndCommunityId(buildingNos,
						identifiedCommunityId);
				if (!existingBuildings.isEmpty()) {
					List<String> conflictNos = existingBuildings.stream().map(Building::getBuildingNo)
							.collect(Collectors.toList());
					result.setSuccess(false);
					result.setMessage("存在重复的楼栋数据，楼栋编号：" + String.join(", ", conflictNos) + "。请选择覆盖模式或跳过模式");
					return result;
				}
			}

			// 注意：不再检查现有数据，因为支持覆盖和跳过模式

			// 批量导入楼栋数据
			List<Building> buildingEntities = importBuildings(buildings, identifiedCommunityId, userId, overwrite,
					skipErrors);
			result.setBuildingCount(buildingEntities.size());

			// 批量导入单元数据
			List<Unit> unitEntities = importUnits(units, buildingEntities, identifiedCommunityId, userId, overwrite,
					skipErrors);
			result.setUnitCount(unitEntities.size());

			// 批量导入房户数据
			List<Household> householdEntities = importHouseholds(households, buildingEntities, unitEntities,
					identifiedCommunityId, userId, overwrite, skipErrors);
			result.setHouseholdCount(householdEntities.size());

			result.setSuccess(true);
			result.setMessage("数据导入成功");

			long endTime = System.currentTimeMillis();
			log.info("社区数据导入成功，社区ID：{}，楼栋：{}个，单元：{}个，房户：{}个，耗时：{}ms", communityId, buildingEntities.size(),
					unitEntities.size(), householdEntities.size(), endTime - startTime);

		} catch (Exception e) {
			long endTime = System.currentTimeMillis();
			log.error("社区数据导入失败，社区ID：{}，耗时：{}ms", communityId, endTime - startTime, e);
			result.setSuccess(false);
			result.setMessage("数据导入失败：" + e.getMessage());
		}

		return result;
	}

	/**
	 * 检查是否存在现有数据
	 */
	private boolean hasExistingData(Long communityId) {
		try {
			// 参数验证
			if (communityId == null) {
				log.warn("社区ID为空，返回false");
				return false;
			}

			// 检查楼栋数据
			long buildingCount = buildingMapper.countBuildings(communityId);
			if (buildingCount > 0) {
				log.info("社区{}已存在{}个楼栋", communityId, buildingCount);
				return true;
			}

			// 检查单元数据
			long unitCount = unitMapper.countUnits(communityId);
			if (unitCount > 0) {
				log.info("社区{}已存在{}个单元", communityId, unitCount);
				return true;
			}

			// 检查房户数据
			long householdCount = householdMapper.countByCommunityId(communityId);
			if (householdCount > 0) {
				log.info("社区{}已存在{}个房户", communityId, householdCount);
				return true;
			}

			return false;
		} catch (Exception e) {
			log.error("检查现有数据失败，社区ID：{}", communityId, e);
			return false; // 生产环境优雅降级
		}
	}

	/**
	 * 导入楼栋数据
	 */
	private List<Building> importBuildings(List<Map<String, Object>> buildings, Long communityId, Long userId,
			Boolean overwrite, Boolean skipErrors) {
		List<Building> buildingEntities = new ArrayList<>();

		try {
			// 参数验证
			if (buildings == null || buildings.isEmpty()) {
				log.warn("楼栋数据为空，返回空列表");
				return buildingEntities;
			}

			for (Map<String, Object> buildingData : buildings) {
				try {
					Building building = new Building();
					building.setCommunityId(communityId);
					building.setBuildingNo((String) buildingData.get("buildingNo"));
					building.setBuildingName((String) buildingData.get("buildingName"));
					building.setFloorCount(Integer.parseInt(buildingData.get("floorCount").toString()));
					building.setUnitCount(Integer.parseInt(buildingData.get("unitCount").toString()));
					building.setUnitsPerFloor(Integer.parseInt(buildingData.get("unitsPerFloor").toString()));

					// 可选字段
					if (buildingData.get("buildingType") != null) {
						// 楼栋类型：1-住宅楼，2-商业楼，3-办公楼，4-综合楼
						String buildingTypeStr = (String) buildingData.get("buildingType");
						building.setBuildingType(buildingTypeStr);
					}
					if (buildingData.get("buildYear") != null) {
						building.setBuildYear(Integer.parseInt(buildingData.get("buildYear").toString()));
					}
					if (buildingData.get("remark") != null) {
						building.setRemark((String) buildingData.get("remark"));
					}

					// 设置默认值
					building.setStatus(1); // 1-启用
					building.setDeleted(0); // 0-未删除，1-已删除
					building.setCreateTime(LocalDateTime.now());
					building.setCreateBy(userId);
					building.setUpdateTime(LocalDateTime.now());
					building.setUpdateBy(userId);

					buildingEntities.add(building);
				} catch (Exception e) {
					log.error("转换楼栋数据失败：{}，错误：{}", buildingData, e.getMessage(), e);
					// 继续处理其他数据，不中断整个导入过程
				}
			}

			// 逐条处理楼栋数据
			if (!buildingEntities.isEmpty()) {
				List<Building> successBuildings = new ArrayList<>();
				int errorCount = 0;

				for (Building building : buildingEntities) {
					try {
						// 先检查数据是否存在
						Building existingBuilding = buildingMapper
								.selectByBuildingNoAndCommunityId(building.getBuildingNo(), communityId);

						// 根据参数决定处理策略
						if (Boolean.TRUE.equals(overwrite)) {
							// 覆盖模式：如果存在则更新，不存在则插入
							if (existingBuilding != null) {
								log.info("发现重复楼栋数据，楼栋编号：{}，执行更新操作", building.getBuildingNo());
								updateExistingBuilding(building, communityId);
								successBuildings.add(building);
								log.info("更新楼栋数据成功，楼栋编号：{}", building.getBuildingNo());
							} else {
								buildingMapper.insert(building);
								successBuildings.add(building);
								log.info("插入楼栋数据成功，楼栋编号：{}", building.getBuildingNo());
							}
						} else if (Boolean.TRUE.equals(skipErrors)) {
							// 跳过模式：如果重复则跳过，不重复则插入
							if (existingBuilding != null) {
								log.warn("跳过重复楼栋数据，楼栋编号：{}", building.getBuildingNo());
								continue;
							} else {
								buildingMapper.insert(building);
								successBuildings.add(building);
								log.info("插入楼栋数据成功，楼栋编号：{}", building.getBuildingNo());
							}
						} else {
							// 严格模式：如果重复则报错，不重复则插入
							if (existingBuilding != null) {
								log.error("楼栋数据重复，楼栋编号：{}", building.getBuildingNo());
								errorCount++;
								throw new RuntimeException("楼栋数据重复，楼栋编号：" + building.getBuildingNo());
							} else {
								buildingMapper.insert(building);
								successBuildings.add(building);
								log.info("插入楼栋数据成功，楼栋编号：{}", building.getBuildingNo());
							}
						}
					} catch (Exception e) {
						log.error("处理楼栋数据失败，楼栋编号：{}，错误：{}", building.getBuildingNo(), e.getMessage(), e);
						errorCount++;
						if (!Boolean.TRUE.equals(skipErrors)) {
							throw new RuntimeException("处理楼栋数据失败：" + e.getMessage(), e);
						}
					}
				}

				buildingEntities = successBuildings;
				log.info("楼栋数据导入完成，成功：{}，错误：{}", successBuildings.size(), errorCount);
			}
		} catch (Exception e) {
			log.error("导入楼栋数据失败", e);
			// 生产环境优雅降级，返回已处理的数据
		}

		return buildingEntities;
	}

	/**
	 * 创建单元实体
	 */
	private Unit createUnitEntity(Map<String, Object> unitData, Building building, Long communityId, Long userId) {
		// 参数验证
		if (building == null || building.getId() == null) {
			throw new RuntimeException("楼栋信息无效，无法创建单元");
		}
		if (communityId == null) {
			throw new RuntimeException("社区ID为空，无法创建单元");
		}
		if (userId == null) {
			throw new RuntimeException("用户ID为空，无法创建单元");
		}

		Unit unit = new Unit();

		// 必填字段 - 确保不为null
		unit.setCommunityId(communityId);
		unit.setBuildingId(building.getId()); // 确保building_id不为null
		unit.setUnitNo(String.valueOf(unitData.get("unitNo")));
		unit.setUnitName((String) unitData.get("unitName"));
		unit.setFloorCount(Integer.parseInt(unitData.get("floorCount").toString()));
		unit.setRoomCount(Integer.parseInt(unitData.get("roomCount").toString()));

		// 设置默认值 - 确保所有必填字段都有值
		unit.setHouseholdCount(0); // 默认房户数量为0
		unit.setHasElevator(0); // 默认无电梯
		unit.setElevatorCount(0); // 默认电梯数量为0
		unit.setDoorAccessType(1); // 默认门禁类型：1-密码
		unit.setStatus(1); // 默认状态：1-正常使用
		unit.setDeleted(0); // 确保deleted字段为0
		unit.setVersion(1); // 默认版本号

		// 可选字段处理
		if (unitData.get("householdCount") != null) {
			unit.setHouseholdCount(Integer.parseInt(unitData.get("householdCount").toString()));
		}

		if (unitData.get("hasElevator") != null) {
			String hasElevator = (String) unitData.get("hasElevator");
			unit.setHasElevator("是".equals(hasElevator) ? 1 : 0);
		}

		if (unitData.get("elevatorCount") != null) {
			unit.setElevatorCount(Integer.parseInt(unitData.get("elevatorCount").toString()));
		}

		if (unitData.get("doorAccessType") != null) {
			// 门禁类型：1-密码，2-刷卡，3-人脸识别，4-指纹
			String doorAccessTypeStr = (String) unitData.get("doorAccessType");
			if ("密码".equals(doorAccessTypeStr)) {
				unit.setDoorAccessType(1);
			} else if ("刷卡".equals(doorAccessTypeStr)) {
				unit.setDoorAccessType(2);
			} else if ("人脸识别".equals(doorAccessTypeStr)) {
				unit.setDoorAccessType(3);
			} else if ("指纹".equals(doorAccessTypeStr)) {
				unit.setDoorAccessType(4);
			}
		}

		if (unitData.get("status") != null) {
			// 状态：0-建设中，1-正常使用，2-维修中，3-停用
			String statusStr = (String) unitData.get("status");
			if ("启用".equals(statusStr) || "正常使用".equals(statusStr)) {
				unit.setStatus(1);
			} else if ("建设中".equals(statusStr)) {
				unit.setStatus(0);
			} else if ("维修中".equals(statusStr)) {
				unit.setStatus(2);
			} else if ("停用".equals(statusStr)) {
				unit.setStatus(3);
			}
		}

		if (unitData.get("remark") != null) {
			unit.setRemark((String) unitData.get("remark"));
		}

		// 设置创建信息
		unit.setCreateBy(userId);
		unit.setCreateTime(LocalDateTime.now());
		unit.setUpdateBy(userId);
		unit.setUpdateTime(LocalDateTime.now());

		return unit;
	}

	/**
	 * 检查单元是否重复
	 */
	private boolean checkUnitDuplicate(String unitNo, Long buildingId) {
		try {
			// 根据楼栋ID和单元编号查询是否存在
			Unit existingUnit = unitMapper.selectByBuildingIdAndUnitNo(buildingId, unitNo);
			boolean isDuplicate = existingUnit != null;
			log.info("检查单元重复，单元编号：{}，楼栋ID：{}，是否重复：{}", unitNo, buildingId, isDuplicate);
			return isDuplicate;
		} catch (Exception e) {
			log.error("检查单元重复失败，单元编号：{}，楼栋ID：{}，错误：{}", unitNo, buildingId, e.getMessage(), e);
			return true; // 查询失败时，为了安全起见，假设存在重复数据
		}
	}

	/**
	 * 更新现有单元数据
	 */
	private void updateExistingUnit(Unit newUnit, Long buildingId) {
		try {
			// 根据楼栋ID和单元编号查询已存在的单元
			Unit existingUnit = unitMapper.selectByBuildingIdAndUnitNo(buildingId, newUnit.getUnitNo());
			if (existingUnit != null) {
				// 更新已存在单元的数据，保留原有的一些字段
				existingUnit.setUnitName(newUnit.getUnitName());
				existingUnit.setFloorCount(newUnit.getFloorCount());
				existingUnit.setRoomCount(newUnit.getRoomCount());
				existingUnit.setHouseholdCount(newUnit.getHouseholdCount());
				existingUnit.setHasElevator(newUnit.getHasElevator());
				existingUnit.setElevatorCount(newUnit.getElevatorCount());
				existingUnit.setDoorAccessType(newUnit.getDoorAccessType());
				existingUnit.setStatus(newUnit.getStatus());
				existingUnit.setRemark(newUnit.getRemark());
				existingUnit.setUpdateBy(newUnit.getUpdateBy());
				existingUnit.setUpdateTime(LocalDateTime.now());
				existingUnit.setDeleted(0); // 确保deleted字段为0

				// 执行更新操作
				unitMapper.updateById(existingUnit);
				log.info("更新单元数据成功，单元ID：{}，单元编号：{}", existingUnit.getId(), newUnit.getUnitNo());
			} else {
				log.warn("未找到要更新的单元数据，楼栋ID：{}，单元编号：{}", buildingId, newUnit.getUnitNo());
				// 如果找不到现有单元，则插入新单元
				unitMapper.insert(newUnit);
				log.info("插入新单元数据成功，单元编号：{}", newUnit.getUnitNo());
			}
		} catch (Exception e) {
			log.error("更新单元数据失败，单元编号：{}，楼栋ID：{}，错误：{}", newUnit.getUnitNo(), buildingId, e.getMessage(), e);
			throw new RuntimeException("更新单元数据失败：" + e.getMessage(), e);
		}
	}

	/**
	 * 检查楼栋是否重复
	 */
	private boolean checkBuildingDuplicate(String buildingNo, Long communityId) {
		try {
			Building existingBuilding = buildingMapper.selectByBuildingNoAndCommunityId(buildingNo, communityId);
			boolean isDuplicate = existingBuilding != null;
			log.info("检查楼栋重复，楼栋编号：{}，社区ID：{}，是否重复：{}", buildingNo, communityId, isDuplicate);
			return isDuplicate;
		} catch (Exception e) {
			log.error("检查楼栋重复失败，楼栋编号：{}，社区ID：{}，错误：{}", buildingNo, communityId, e.getMessage(), e);
			// 查询失败时，为了安全起见，假设存在重复数据，避免直接插入导致约束冲突
			return true;
		}
	}

	/**
	 * 更新现有楼栋数据
	 */
	private void updateExistingBuilding(Building newBuilding, Long communityId) {
		try {
			Building existingBuilding = buildingMapper.selectByBuildingNoAndCommunityId(newBuilding.getBuildingNo(),
					communityId);
			log.info("查询现有楼栋，楼栋编号：{}，社区ID：{}，查询结果：{}", newBuilding.getBuildingNo(), communityId,
					existingBuilding != null ? "找到" : "未找到");

			if (existingBuilding != null) {
				log.info("现有楼栋信息，ID：{}，deleted：{}，版本：{}", existingBuilding.getId(), existingBuilding.getDeleted(),
						existingBuilding.getVersion());

				// 保留原有ID，更新其他字段
				newBuilding.setId(existingBuilding.getId());
				newBuilding.setCreateBy(existingBuilding.getCreateBy());
				newBuilding.setCreateTime(existingBuilding.getCreateTime());
				newBuilding.setUpdateBy(SecurityUtils.getCurrentUserId());
				newBuilding.setUpdateTime(LocalDateTime.now());
				newBuilding.setVersion(existingBuilding.getVersion() + 1);
				newBuilding.setDeleted(0); // 确保deleted字段为0

				log.info("准备更新楼栋，新楼栋deleted：{}，版本：{}", newBuilding.getDeleted(), newBuilding.getVersion());

				buildingMapper.updateById(newBuilding);
				log.info("更新楼栋数据成功，楼栋编号：{}，楼栋ID：{}", newBuilding.getBuildingNo(), existingBuilding.getId());
			} else {
				// 如果没有找到现有楼栋，直接插入新楼栋
				buildingMapper.insert(newBuilding);
				log.info("插入新楼栋数据成功，楼栋编号：{}", newBuilding.getBuildingNo());
			}
		} catch (Exception e) {
			log.error("更新楼栋数据失败，楼栋编号：{}，社区ID：{}，错误：{}", newBuilding.getBuildingNo(), communityId, e.getMessage(), e);
			throw new RuntimeException("更新楼栋数据失败：" + e.getMessage(), e);
		}
	}

	/**
	 * 删除现有楼栋数据
	 */
	private void deleteExistingBuilding(String buildingNo, Long communityId) {
		try {
			List<Building> existingBuildings = buildingMapper
					.selectByBuildingNosAndCommunityId(Collections.singletonList(buildingNo), communityId);
			if (!existingBuildings.isEmpty()) {
				for (Building existingBuilding : existingBuildings) {
					buildingMapper.deleteById(existingBuilding.getId());
					log.info("删除现有楼栋数据，楼栋编号：{}，楼栋ID：{}", buildingNo, existingBuilding.getId());
				}
			}
		} catch (Exception e) {
			log.error("删除现有楼栋数据失败，楼栋编号：{}，社区ID：{}，错误：{}", buildingNo, communityId, e.getMessage(), e);
			throw new RuntimeException("删除现有楼栋数据失败：" + e.getMessage(), e);
		}
	}

	/**
	 * 导入单元数据
	 */
	private List<Unit> importUnits(List<Map<String, Object>> units, List<Building> buildings, Long communityId,
			Long userId, Boolean overwrite, Boolean skipErrors) {
		List<Unit> successUnits = new ArrayList<>();
		int errorCount = 0;

		// 构建楼栋映射
		Map<String, Building> buildingMap = buildings.stream()
				.collect(Collectors.toMap(Building::getBuildingNo, building -> building));

		for (Map<String, Object> unitData : units) {
			try {
				String buildingNo = (String) unitData.get("buildingNo");
				Building building = buildingMap.get(buildingNo);

				if (building == null) {
					log.warn("单元数据对应的楼栋不存在，楼栋编号：{}，单元编号：{}", buildingNo, unitData.get("unitNo"));
					errorCount++;
					if (!Boolean.TRUE.equals(skipErrors)) {
						throw new RuntimeException("单元数据对应的楼栋不存在，楼栋编号：" + buildingNo);
					}
					continue;
				}

				String unitNo = String.valueOf(unitData.get("unitNo"));

				// 先检查数据是否存在
				boolean isDuplicate = checkUnitDuplicate(unitNo, building.getId());

				// 根据参数决定处理策略
				if (Boolean.TRUE.equals(overwrite)) {
					// 覆盖模式：如果存在则更新，不存在则插入
					Unit unit = createUnitEntity(unitData, building, communityId, userId);
					if (isDuplicate) {
						log.info("发现重复单元数据，单元编号：{}，执行更新操作", unitNo);
						updateExistingUnit(unit, building.getId());
						// 更新后重新查询获取ID
						Unit updatedUnit = unitMapper.selectByBuildingIdAndUnitNo(building.getId(), unitNo);
						if (updatedUnit != null) {
							successUnits.add(updatedUnit);
							log.info("更新单元数据成功，单元编号：{}，单元ID：{}", unitNo, updatedUnit.getId());
						} else {
							log.error("更新单元数据后查询失败，单元编号：{}", unitNo);
							errorCount++;
						}
					} else {
						unitMapper.insert(unit);
						// 插入后重新查询获取ID
						Unit savedUnit = unitMapper.selectByBuildingIdAndUnitNo(building.getId(), unitNo);
						if (savedUnit != null) {
							successUnits.add(savedUnit);
							log.info("插入单元数据成功，单元编号：{}，单元ID：{}", unitNo, savedUnit.getId());
						} else {
							log.error("插入单元数据后查询失败，单元编号：{}", unitNo);
							errorCount++;
						}
					}
				} else if (Boolean.TRUE.equals(skipErrors)) {
					// 跳过模式：如果重复则跳过，不重复则插入
					if (isDuplicate) {
						log.warn("跳过重复单元数据，单元编号：{}", unitNo);
						// 即使跳过，也要查询现有单元的ID，用于后续房户导入
						Unit existingUnit = unitMapper.selectByBuildingIdAndUnitNo(building.getId(), unitNo);
						if (existingUnit != null) {
							successUnits.add(existingUnit);
							log.info("使用现有单元数据，单元编号：{}，单元ID：{}", unitNo, existingUnit.getId());
						}
						continue;
					} else {
						Unit unit = createUnitEntity(unitData, building, communityId, userId);
						unitMapper.insert(unit);
						// 插入后重新查询获取ID
						Unit savedUnit = unitMapper.selectByBuildingIdAndUnitNo(building.getId(), unitNo);
						if (savedUnit != null) {
							successUnits.add(savedUnit);
							log.info("插入单元数据成功，单元编号：{}，单元ID：{}", unitNo, savedUnit.getId());
						} else {
							log.error("插入单元数据后查询失败，单元编号：{}", unitNo);
							errorCount++;
						}
					}
				} else {
					// 严格模式：如果重复则报错，不重复则插入
					if (isDuplicate) {
						log.error("单元数据重复，单元编号：{}", unitNo);
						errorCount++;
						throw new RuntimeException("单元数据重复，单元编号：" + unitNo);
					} else {
						Unit unit = createUnitEntity(unitData, building, communityId, userId);
						unitMapper.insert(unit);
						// 插入后重新查询获取ID
						Unit savedUnit = unitMapper.selectByBuildingIdAndUnitNo(building.getId(), unitNo);
						if (savedUnit != null) {
							successUnits.add(savedUnit);
							log.info("插入单元数据成功，单元编号：{}，单元ID：{}", unitNo, savedUnit.getId());
						} else {
							log.error("插入单元数据后查询失败，单元编号：{}", unitNo);
							errorCount++;
						}
					}
				}
			} catch (Exception e) {
				log.error("处理单元数据失败，单元编号：{}，错误：{}", unitData.get("unitNo"), e.getMessage(), e);
				errorCount++;
				if (!Boolean.TRUE.equals(skipErrors)) {
					throw new RuntimeException("处理单元数据失败：" + e.getMessage(), e);
				}
			}
		}

		log.info("单元数据导入完成，成功：{}，错误：{}", successUnits.size(), errorCount);
		return successUnits;
	}

	/**
	 * 导入房户数据
	 */
	private List<Household> importHouseholds(List<Map<String, Object>> households, List<Building> buildings,
			List<Unit> units, Long communityId, Long userId, Boolean overwrite, Boolean skipErrors) {
		List<Household> householdEntities = new ArrayList<>();
		int errorCount = 0;

		// 构建楼栋和单元映射
		Map<String, Building> buildingMap = buildings.stream()
				.collect(Collectors.toMap(Building::getBuildingNo, building -> building));

		Map<String, Unit> unitMap = new HashMap<>();
		for (Unit unit : units) {
			// 通过楼栋ID查找对应的楼栋
			Building building = null;
			for (Building b : buildings) {
				if (b.getId().equals(unit.getBuildingId())) {
					building = b;
					break;
				}
			}
			if (building != null) {
				unitMap.put(building.getBuildingNo() + "-" + unit.getUnitNo(), unit);
			}
		}

		for (Map<String, Object> householdData : households) {
			try {
				String buildingNo = (String) householdData.get("buildingNo");
				int unitNo = Integer.parseInt(householdData.get("unitNo").toString());
				String unitKey = buildingNo + "-" + unitNo;

				Building building = buildingMap.get(buildingNo);
				Unit unit = unitMap.get(unitKey);

				if (building == null) {
					log.warn("房户数据对应的楼栋不存在，楼栋编号：{}，房户编码：{}", buildingNo, householdData.get("householdCode"));
					errorCount++;
					continue;
				}

				if (unit == null) {
					log.warn("房户数据对应的单元不存在，楼栋编号：{}，单元编号：{}，房户编码：{}", buildingNo, unitNo,
							householdData.get("householdCode"));
					errorCount++;
					continue;
				}

				String householdCode = (String) householdData.get("householdCode");

				// 先检查房户是否重复
				boolean isDuplicate = checkHouseholdDuplicate(householdCode, unit.getId());

				// 根据参数决定处理策略
				if (Boolean.TRUE.equals(overwrite)) {
					// 覆盖模式：如果存在则更新，不存在则插入
					Household household = createHouseholdEntity(householdData, building, unit, communityId, userId);
					if (isDuplicate) {
						log.info("发现重复房户数据，房户编码：{}，执行更新操作", householdCode);
						updateExistingHousehold(household, unit.getId());
						log.info("更新房户数据成功，房户编码：{}", householdCode);
					} else {
						householdMapper.insert(household);
						log.info("插入房户数据成功，房户编码：{}", householdCode);
					}
					householdEntities.add(household);
				} else if (Boolean.TRUE.equals(skipErrors)) {
					// 跳过模式：如果重复则跳过，不重复则插入
					if (isDuplicate) {
						log.warn("跳过重复房户数据，房户编码：{}", householdCode);
						continue;
					} else {
						Household household = createHouseholdEntity(householdData, building, unit, communityId, userId);
						householdMapper.insert(household);
						log.info("插入房户数据成功，房户编码：{}", householdCode);
						householdEntities.add(household);
					}
				} else {
					// 严格模式：如果重复则报错，不重复则插入
					if (isDuplicate) {
						log.error("房户数据重复，房户编码：{}", householdCode);
						errorCount++;
						throw new RuntimeException("房户数据重复，房户编码：" + householdCode);
					} else {
						Household household = createHouseholdEntity(householdData, building, unit, communityId, userId);
						householdMapper.insert(household);
						log.info("插入房户数据成功，房户编码：{}", householdCode);
						householdEntities.add(household);
					}
				}

			} catch (Exception e) {
				log.error("处理房户数据失败，房户编码：{}，错误：{}", householdData.get("householdCode"), e.getMessage(), e);
				errorCount++;
			}
		}

		log.info("房户数据导入完成，成功：{}，错误：{}", householdEntities.size(), errorCount);
		return householdEntities;
	}

	/**
	 * 创建房户实体
	 */
	private Household createHouseholdEntity(Map<String, Object> householdData, Building building, Unit unit,
			Long communityId, Long userId) {
		// 参数验证
		if (building == null || building.getId() == null) {
			throw new RuntimeException("楼栋信息无效，无法创建房户");
		}
		if (unit == null || unit.getId() == null) {
			throw new RuntimeException("单元信息无效，无法创建房户");
		}
		if (communityId == null) {
			throw new RuntimeException("社区ID为空，无法创建房户");
		}
		if (userId == null) {
			throw new RuntimeException("用户ID为空，无法创建房户");
		}

		Household household = new Household();

		// 必填字段 - 确保不为null
		household.setCommunityId(communityId);
		household.setBuildingId(building.getId());
		household.setUnitId(unit.getId());
		household.setHouseholdCode((String) householdData.get("householdCode"));
		household.setRoomNumber(householdData.get("roomNumber").toString());
		household.setFloorNumber(Integer.parseInt(householdData.get("floorNumber").toString()));
		household.setArea(BigDecimal.valueOf(Double.parseDouble(householdData.get("area").toString())));

		// 设置默认值 - 确保所有必填字段都有值
		household.setRoomType(2); // 默认两室
		household.setStatus(1); // 默认已入住
		household.setDeleted(0); // 确保deleted字段为0
		household.setVersion(1); // 默认版本号

		// 可选字段处理
		if (householdData.get("houseType") != null) {
			// 房间类型：1-一室，2-两室，3-三室，4-四室及以上
			String houseTypeStr = (String) householdData.get("houseType");
			household.setHouseTypeName(houseTypeStr); // 设置户型名称
			if ("一室".equals(houseTypeStr)) {
				household.setRoomType(1);
			} else if ("两室".equals(houseTypeStr)) {
				household.setRoomType(2);
			} else if ("三室".equals(houseTypeStr)) {
				household.setRoomType(3);
			} else if ("四室及以上".equals(houseTypeStr)) {
				household.setRoomType(4);
			}
		}

		if (householdData.get("orientation") != null) {
			household.setOrientation((String) householdData.get("orientation"));
		}

		if (householdData.get("remark") != null) {
			household.setDescription((String) householdData.get("remark"));
		}

		// 设置创建信息
		household.setCreateBy(userId);
		household.setCreateTime(LocalDateTime.now());
		household.setUpdateBy(userId);
		household.setUpdateTime(LocalDateTime.now());

		return household;
	}

	/**
	 * 检查房户是否重复
	 */
	private boolean checkHouseholdDuplicate(String householdCode, Long unitId) {
		try {
			// 根据房户编码和单元ID查询是否存在
			Household existingHousehold = householdMapper.selectByHouseholdCodeAndUnitId(householdCode, unitId);
			boolean isDuplicate = existingHousehold != null;
			log.info("检查房户重复，房户编码：{}，单元ID：{}，是否重复：{}", householdCode, unitId, isDuplicate);
			return isDuplicate;
		} catch (Exception e) {
			log.error("检查房户重复失败，房户编码：{}，单元ID：{}，错误：{}", householdCode, unitId, e.getMessage(), e);
			return true; // 查询失败时，为了安全起见，假设存在重复数据
		}
	}

	/**
	 * 更新已存在的房户数据
	 */
	private void updateExistingHousehold(Household newHousehold, Long unitId) {
		try {
			// 根据房户编码和单元ID查询已存在的房户
			Household existingHousehold = householdMapper
					.selectByHouseholdCodeAndUnitId(newHousehold.getHouseholdCode(), unitId);
			if (existingHousehold != null) {
				// 更新已存在房户的数据，保留原有的一些字段
				existingHousehold.setRoomNumber(newHousehold.getRoomNumber());
				existingHousehold.setFloorNumber(newHousehold.getFloorNumber());
				existingHousehold.setArea(newHousehold.getArea());
				existingHousehold.setRoomType(newHousehold.getRoomType());
				existingHousehold.setHouseTypeName(newHousehold.getHouseTypeName());
				existingHousehold.setOrientation(newHousehold.getOrientation());
				existingHousehold.setStatus(newHousehold.getStatus());
				existingHousehold.setDescription(newHousehold.getDescription());
				existingHousehold.setUpdateBy(newHousehold.getUpdateBy());
				existingHousehold.setUpdateTime(LocalDateTime.now());
				existingHousehold.setDeleted(0); // 确保deleted字段为0

				// 执行更新操作
				householdMapper.updateById(existingHousehold);
				log.info("更新房户数据成功，房户ID：{}，房户编码：{}", existingHousehold.getId(), newHousehold.getHouseholdCode());
			} else {
				log.warn("未找到要更新的房户数据，房户编码：{}，单元ID：{}", newHousehold.getHouseholdCode(), unitId);
				// 如果找不到现有房户，则插入新房户
				householdMapper.insert(newHousehold);
				log.info("插入新房户数据成功，房户编码：{}", newHousehold.getHouseholdCode());
			}
		} catch (Exception e) {
			log.error("更新房户数据失败，房户编码：{}，单元ID：{}，错误：{}", newHousehold.getHouseholdCode(), unitId, e.getMessage(), e);
			throw new RuntimeException("更新房户数据失败：" + e.getMessage(), e);
		}
	}

	/**
	 * 智能识别社区 优先使用用户手动选择的社区ID，如果用户未选择则从模板数据中智能识别
	 * 
	 * @param buildings               楼栋数据
	 * @param units                   单元数据
	 * @param households              房户数据
	 * @param userSelectedCommunityId 用户手动选择的社区ID
	 * @return 识别到的社区ID，如果识别失败返回null
	 */
	private Long identifyCommunity(List<Map<String, Object>> buildings, List<Map<String, Object>> units,
			List<Map<String, Object>> households, Long userSelectedCommunityId) {
		try {
			// 如果用户手动选择了社区，优先使用用户选择的社区ID
			if (userSelectedCommunityId != null) {
				log.info("用户手动选择了社区，社区ID：{}", userSelectedCommunityId);

				// 验证用户选择的社区是否在权限范围内
				if (validateUserSelectedCommunity(userSelectedCommunityId)) {
					log.info("用户选择的社区验证通过，使用社区ID：{}", userSelectedCommunityId);
					return userSelectedCommunityId;
				} else {
					log.warn("用户选择的社区不在权限范围内，社区ID：{}", userSelectedCommunityId);
					// 如果用户选择的社区不在权限范围内，继续使用智能识别
				}
			}

			// 如果用户未选择社区或选择的社区无效，则从模板数据中智能识别
			log.info("开始从模板数据中智能识别社区");

			// 参数验证
			if (buildings == null || buildings.isEmpty()) {
				log.warn("楼栋数据为空，无法识别社区");
				return null;
			}

			// 从楼栋数据中提取社区名称
			String communityName = extractCommunityName(buildings);
			if (communityName == null || communityName.trim().isEmpty()) {
				log.warn("无法从楼栋数据中提取社区名称");
				return null;
			}

			log.info("从模板数据中识别到社区名称：{}", communityName);

			// 根据社区名称查询社区
			Community community = findCommunityByName(communityName);
			if (community == null) {
				log.warn("未找到社区：{}，请检查社区名称或先创建社区", communityName);
				return null;
			}

			log.info("成功识别社区，社区ID：{}，社区名称：{}", community.getId(), community.getCommunityName());
			return community.getId();

		} catch (Exception e) {
			log.error("社区识别失败", e);
			return null;
		}
	}

	/**
	 * 从楼栋数据中提取社区名称
	 * 
	 * @param buildings 楼栋数据列表
	 * @return 社区名称
	 */
	private String extractCommunityName(List<Map<String, Object>> buildings) {
		if (buildings == null || buildings.isEmpty()) {
			return null;
		}

		// 从第一条楼栋数据中提取社区名称
		Map<String, Object> firstBuilding = buildings.get(0);
		Object communityNameObj = firstBuilding.get("communityName");

		if (communityNameObj == null) {
			return null;
		}

		String communityName = communityNameObj.toString().trim();
		if (communityName.isEmpty()) {
			return null;
		}

		// 验证所有楼栋数据的社区名称是否一致
		for (Map<String, Object> building : buildings) {
			Object nameObj = building.get("communityName");
			if (nameObj == null || !communityName.equals(nameObj.toString().trim())) {
				log.warn("楼栋数据中的社区名称不一致，第一条：{}，当前：{}", communityName, nameObj);
				return null;
			}
		}

		return communityName;
	}

	/**
	 * 根据社区名称查询社区（考虑用户权限）
	 * 
	 * @param communityName 社区名称
	 * @return 社区实体
	 */
	private Community findCommunityByName(String communityName) {
		try {
			// 参数验证
			if (communityName == null || communityName.trim().isEmpty()) {
				log.warn("社区名称为空，无法查询");
				return null;
			}

			// 获取当前用户ID
			Long currentUserId = SecurityUtils.getCurrentUserId();
			if (currentUserId == null) {
				log.warn("当前用户未登录，无法进行权限验证");
				return null;
			}

			// 获取用户数据权限信息
			DataScopeInfo dataScopeInfo = dataScopeFeign.getUserDataScope(currentUserId);
			if (dataScopeInfo == null) {
				log.warn("获取用户数据权限信息失败，用户ID：{}", currentUserId);
				return null;
			}

			// 获取用户可访问的社区ID列表
			List<Long> accessibleCommunityIds = dataScopeInfo.getCommunityIds();
			if (accessibleCommunityIds == null || accessibleCommunityIds.isEmpty()) {
				log.warn("用户无社区权限，用户ID：{}，社区名称：{}", currentUserId, communityName);
				return null;
			}

			log.info("用户可访问的社区数量：{}，社区名称：{}", accessibleCommunityIds.size(), communityName);

			// 在用户有权限的社区中查找匹配的社区
			Community matchedCommunity = findCommunityInAccessibleList(communityName.trim(), accessibleCommunityIds);

			if (matchedCommunity != null) {
				log.info("在用户权限范围内找到社区：{}，ID：{}", communityName, matchedCommunity.getId());
				return matchedCommunity;
			}

			log.warn("在用户权限范围内未找到社区：{}，用户ID：{}", communityName, currentUserId);
			return null;

		} catch (Exception e) {
			log.error("查询社区失败，社区名称：{}", communityName, e);
			return null;
		}
	}

	/**
	 * 在用户可访问的社区列表中查找匹配的社区
	 * 
	 * @param communityName          社区名称
	 * @param accessibleCommunityIds 用户可访问的社区ID列表
	 * @return 匹配的社区实体
	 */
	private Community findCommunityInAccessibleList(String communityName, List<Long> accessibleCommunityIds) {
		try {
			// 精确匹配查询
			LambdaQueryWrapper<Community> queryWrapper = new LambdaQueryWrapper<>();
			queryWrapper.eq(Community::getCommunityName, communityName);
			queryWrapper.eq(Community::getDeleted, 0);
			queryWrapper.eq(Community::getStatus, 1); // 只查询启用状态的社区
			queryWrapper.in(Community::getId, accessibleCommunityIds);

			Community community = communityMapper.selectOne(queryWrapper);
			if (community != null) {
				log.info("精确匹配找到社区：{}，ID：{}", communityName, community.getId());
				return community;
			}

			// 如果精确匹配失败，尝试模糊匹配
			queryWrapper = new LambdaQueryWrapper<>();
			queryWrapper.like(Community::getCommunityName, communityName);
			queryWrapper.eq(Community::getDeleted, 0);
			queryWrapper.eq(Community::getStatus, 1);
			queryWrapper.in(Community::getId, accessibleCommunityIds);

			List<Community> communities = communityMapper.selectList(queryWrapper);
			if (communities.size() == 1) {
				community = communities.get(0);
				log.info("通过模糊匹配找到社区：{}，ID：{}", communityName, community.getId());
				return community;
			} else if (communities.size() > 1) {
				log.warn("在用户权限范围内找到多个匹配的社区：{}，数量：{}，请使用更精确的社区名称", communityName, communities.size());
				return null;
			}

			log.warn("在用户权限范围内未找到社区：{}", communityName);
			return null;

		} catch (Exception e) {
			log.error("在用户权限范围内查询社区失败，社区名称：{}", communityName, e);
			return null;
		}
	}

	/**
	 * 验证用户选择的社区是否在权限范围内
	 * 
	 * @param communityId 社区ID
	 * @return 是否在权限范围内
	 */
	private boolean validateUserSelectedCommunity(Long communityId) {
		try {
			if (communityId == null) {
				return false;
			}

			// 获取当前用户ID
			Long currentUserId = SecurityUtils.getCurrentUserId();
			if (currentUserId == null) {
				log.warn("当前用户未登录，无法验证社区权限");
				return false;
			}

			// 获取用户数据权限信息
			DataScopeInfo dataScopeInfo = dataScopeFeign.getUserDataScope(currentUserId);
			if (dataScopeInfo == null) {
				log.warn("获取用户数据权限信息失败，用户ID：{}", currentUserId);
				return false;
			}

			// 获取用户可访问的社区ID列表
			List<Long> accessibleCommunityIds = dataScopeInfo.getCommunityIds();
			if (accessibleCommunityIds == null || accessibleCommunityIds.isEmpty()) {
				log.warn("用户无社区权限，用户ID：{}", currentUserId);
				return false;
			}

			// 检查用户选择的社区是否在权限范围内
			boolean hasPermission = accessibleCommunityIds.contains(communityId);
			if (hasPermission) {
				log.info("用户选择的社区在权限范围内，社区ID：{}，用户ID：{}", communityId, currentUserId);
			} else {
				log.warn("用户选择的社区不在权限范围内，社区ID：{}，用户ID：{}", communityId, currentUserId);
			}

			return hasPermission;

		} catch (Exception e) {
			log.error("验证用户选择的社区权限失败，社区ID：{}", communityId, e);
			return false;
		}
	}

	/**
	 * 获取用户可访问的社区名称列表
	 * 
	 * @param accessibleCommunityIds 用户可访问的社区ID列表
	 * @return 社区名称列表
	 */
	private List<String> getAccessibleCommunityNames(List<Long> accessibleCommunityIds) {
		try {
			if (accessibleCommunityIds == null || accessibleCommunityIds.isEmpty()) {
				return Collections.emptyList();
			}

			LambdaQueryWrapper<Community> queryWrapper = new LambdaQueryWrapper<>();
			queryWrapper.in(Community::getId, accessibleCommunityIds);
			queryWrapper.eq(Community::getDeleted, 0);
			queryWrapper.eq(Community::getStatus, 1);
			queryWrapper.select(Community::getCommunityName);

			List<Community> communities = communityMapper.selectList(queryWrapper);
			return communities.stream().map(Community::getCommunityName)
					.filter(name -> name != null && !name.trim().isEmpty()).collect(Collectors.toList());

		} catch (Exception e) {
			log.error("获取用户可访问的社区名称列表失败", e);
			return Collections.emptyList();
		}
	}

	/**
	 * 导入结果类
	 */
	public static class ImportResult {
		private boolean success;
		private String message;
		private int buildingCount;
		private int unitCount;
		private int householdCount;
		private List<DataValidationUtils.ValidationError> buildingErrors;
		private List<DataValidationUtils.ValidationError> unitErrors;
		private List<DataValidationUtils.ValidationError> householdErrors;

		// Getters and Setters
		public boolean isSuccess() {
			return success;
		}

		public void setSuccess(boolean success) {
			this.success = success;
		}

		public String getMessage() {
			return message;
		}

		public void setMessage(String message) {
			this.message = message;
		}

		public int getBuildingCount() {
			return buildingCount;
		}

		public void setBuildingCount(int buildingCount) {
			this.buildingCount = buildingCount;
		}

		public int getUnitCount() {
			return unitCount;
		}

		public void setUnitCount(int unitCount) {
			this.unitCount = unitCount;
		}

		public int getHouseholdCount() {
			return householdCount;
		}

		public void setHouseholdCount(int householdCount) {
			this.householdCount = householdCount;
		}

		public List<DataValidationUtils.ValidationError> getBuildingErrors() {
			return buildingErrors;
		}

		public void setBuildingErrors(List<DataValidationUtils.ValidationError> buildingErrors) {
			this.buildingErrors = buildingErrors;
		}

		public List<DataValidationUtils.ValidationError> getUnitErrors() {
			return unitErrors;
		}

		public void setUnitErrors(List<DataValidationUtils.ValidationError> unitErrors) {
			this.unitErrors = unitErrors;
		}

		public List<DataValidationUtils.ValidationError> getHouseholdErrors() {
			return householdErrors;
		}

		public void setHouseholdErrors(List<DataValidationUtils.ValidationError> householdErrors) {
			this.householdErrors = householdErrors;
		}
	}
}
